{{- define "mwh_common_global" }}
  {{- $context := index . 0 }}
  {{- $prefix := index . 1 }}
  {{- $versionInfo := get $context.Values.istio.internal.versionMap $context.Values.istio.internal.globalVersion }}
  {{- $revision := get $versionInfo "revision" }}
- name: {{ $prefix }}sidecar-injector.istio.io
  admissionReviewVersions:
  - v1
  clientConfig:
    caBundle: {{ $context.Values.istio.internal.ca.cert | b64enc }}
    service:
      name: istiod-{{ $revision }}
      namespace: d8-istio
      path: "/inject"
      port: 443
  reinvocationPolicy: Never
  failurePolicy: Fail
  matchPolicy: Exact
  rules:
    - apiGroups: [""]
      apiVersions: ["v1"]
      operations: [ "CREATE" ]
      resources: ["pods"]
      scope: '*'
  sideEffects: None
  timeoutSeconds: 30
{{- end }}

---
{{- $versionInfo := get .Values.istio.internal.versionMap .Values.istio.internal.globalVersion }}
{{- $fullVersion := get $versionInfo "fullVersion" }}
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
  name: d8-istio-sidecar-injector-global
  {{- include "helm_lib_module_labels" (list . (dict "istio.deckhouse.io/full-version" $fullVersion) ) | nindent 2 }}
webhooks:
{{- /* Case 1: Namespace-wide injection */}}
{{ include "mwh_common_global" (list . "namespace-") }}
  namespaceSelector:
    matchExpressions:
    - key: istio-injection
      operator: In
      values:
      - enabled
    - key: istio.io/rev
      operator: DoesNotExist
  objectSelector:
    matchExpressions:
    - key: sidecar.istio.io/inject
      operator: NotIn
      values:
      - "false"
{{- /* Case 2: Injection for individual pods */}}
{{ include "mwh_common_global" (list . "object-") }}
  namespaceSelector:
    matchExpressions:
      - key: istio-injection
        operator: DoesNotExist
      - key: istio.io/rev
        operator: DoesNotExist
  objectSelector:
    matchExpressions:
      - key: sidecar.istio.io/inject
        operator: In
        values:
          - "true"
      - key: istio.io/rev
        operator: DoesNotExist

